package json.val;

import json.Util;

import java.util.HashMap;
import java.util.Map;

public class ObjectVal extends JsonVal {
    private Map<StringVal, JsonVal> keyValueMap;

    public ObjectVal() {
        keyValueMap = new HashMap<>();
    }
    public ObjectVal(Map<StringVal, JsonVal> keyValueMap) {
        this.keyValueMap = keyValueMap;
    }

    public void putKeyVal(String key, String val) {
        StringVal newKey = new StringVal(key);
        StringVal newValue = new StringVal(val);
        keyValueMap.put(newKey, newValue);
    }
    public void putKeyVal(String key, JsonVal val) {
        StringVal newKey = new StringVal(key);
        keyValueMap.put(newKey, val);
    }

    public JsonVal getValue(String key){
        StringVal stringVal = new StringVal(key);
        return keyValueMap.get(stringVal);
    }

    public Map<StringVal, JsonVal> getKeyValueMap() {
        return keyValueMap;
    }

    @Override
    public String serializeSelf(int tabNum) {
        StringBuilder sb = new StringBuilder();
        sb.append("{").append("\n");
        boolean isFirst = true;
        for (StringVal key : keyValueMap.keySet()){
            if (isFirst){
                isFirst = false;
            }
            else {
                sb.append(",\n");
            }
            Util.printTab(tabNum, sb);
            sb.append(key).append(": ");
            sb.append(keyValueMap.get(key).serializeSelf(tabNum+1));
        }
        sb.append("\n");
        Util.printTab(tabNum-1, sb);
        sb.append("}");
        return sb.toString();
    }

    @Override
    public String toString() {
        return serializeSelf(1);
    }
}
